<?php
/**
 * This file is part of Project.
 *
 * @link     https://www.xxx.com
 * @contact  xxxx@xxx.com
 */

namespace App\Repository;


use App\Model\CatalogModel;

class CatalogRepository extends BaseRepository
{
    public function __construct()
    {
        $this->model = new CatalogModel();
    }

    /**
     * Notes: 获取目录
     * Author: Bruce.z
     * DateTime: 2022/1/4 17:45
     * @param int $pid
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getList($pid = 0, $page=1, $size=10):array
    {
        $offset = max(0, ($page-1)*$size);
        return $this->_searchFactor(['pid'=>$pid])
            ->offset($offset)
            ->limit($size)
            ->get()
            ->toArray();
    }

    /**
     * Notes: 获取分类下的目录数量
     * Author: Bruce.z
     * DateTime: 2022/1/4 18:19
     * @param int $pid
     * @return int
     */
    public function getCount($pid = 0):int
    {
        return $this->_searchFactor(['pid'=>$pid])->count();
    }

    /**
     * Notes: 获取分类树
     * @param int $depth 1|2|3
     * @return array
     */
    public function getTree(int $depth = 3) : array
    {
        if($depth == 2){
            return $this->nextTree(0);
        }else{
            $level = $this->_searchFactor(['pid'=>0])->get(['pid','name','id'])->toArray();
            if($depth == 1) return $level;

            foreach ($level as &$item){
                $item['children'] = $this->nextTree($item['id']);
            }

            return $level;
        }
    }

    private function nextTree($pid): array
    {
        $rows = $this->_searchFactor(['pid'=>$pid])->get(['pid','name','id'])->toArray();
        if(empty($rows)) return [];

        $ids = array_column($rows, 'id');
        $level_next = $this->_searchFactor(['pid'=>$ids])->get(['pid','name','id'])->toArray();

        foreach ($rows as &$v){
            foreach ($level_next as $value){
                if($v['id'] == $value['pid']){
                    $v['children'][] = $value;
                }
            }
        }

        return $rows;
    }

    /**
     * @param int $depth
     * @return array
     */
    public function makeSelectTree(int $depth = 3) :array
    {
        $tree = $this->getTree($depth);

        return [[
            'id'=>0,
            'name'=>'首页',
            'children'=>$tree
        ]];
    }
}
